/*
 *所有关于v_questionnaireresult类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*v_questionnaireresultService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.AppManager.IRepositories;
using VOL.Core.Configuration;
using VOL.Core.Enums;
using VOL.Core.Extensions;
using VOL.Core.Utilities;
using VOL.Entity.DomainModels;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using OfficeOpenXml;

namespace VOL.AppManager.Services
{
    public partial class v_questionnaireresultService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Iv_questionnaireresultRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public v_questionnaireresultService(
            Iv_questionnaireresultRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        /// <summary>
        /// 获取table2的数据
        /// </summary>
        /// <param name="loadData"></param>
        /// <returns></returns>
        public string GenerateDataToExcel(PageDataOptions options)
        {
            List<SearchParameters> searchParametersList = new List<SearchParameters>();
            if (!string.IsNullOrEmpty(options.Wheres))
            {
                try
                {
                    searchParametersList = options.Wheres.DeserializeObject<List<SearchParameters>>();
                }
                catch { }
            }

            var typeid = (searchParametersList == null || searchParametersList.Count() <= 0) ? "0" : searchParametersList[0].Value;
            var data = (typeid == "0") ?
                       repository.Find(x => 1 == 1) :
                       repository.Find(x => x.typeid == searchParametersList[0].Value);

            string fileName = "questnaire-" + DateTime.Now.ToString("yyyyMMddHHssmm") + ".xlsx";
            string folder = DateTime.Now.ToString("yyyyMMdd");
            string savePath = $"Download/ExcelExport/{folder}/".MapPath();

            this.ExportBaseData(data, savePath, fileName);
            string fullPath = savePath + fileName;
            if (typeid == "0" || typeid == "1")
            {
                var jiguan = data.Where(d => d.typeid == "1").ToList();
                this.ExportDetailData(jiguan, fullPath, "党政机关");
            }
            if (typeid == "0" || typeid == "2")
            {
                var yiliao = data.Where(d => d.typeid == "2").ToList();
                this.ExportDetailData(yiliao, fullPath, "医疗卫生机构");
            }

            return (savePath + "/" + fileName); // .EncryptDES(AppSetting.Secret.ExportFile);
        }

        private void ExportBaseData(List<v_questionnaireresult> list, string savePath, string fileName)
        {
            List<string> ignoreColumn = new List<string>();
            string[] exportColumn = new string[] { "typename", "groupname", "unitname", "questresult", "Modifier", "ModifyDate" };
            EPPlusHelper.Export(list, exportColumn, ignoreColumn, savePath, fileName);
        }

        private void ExportDetailData(List<v_questionnaireresult> list, string fullPath, string sheetname)
        {
            using (ExcelPackage package = new ExcelPackage(new FileInfo(fullPath)))
            {
                var worksheet = package.Workbook.Worksheets.Add(sheetname);

                package.Save();
            }

            foreach (var item in list)
            {
                Console.WriteLine(item.answerscontent);
                QuestResult result = JsonConvert.DeserializeObject<QuestResult>(item.answerscontent);
            }
        }

        public List<v_questionnaireresult> GetQuestionnairesListWithType(string type)
        {
            List<v_questionnaireresult> result = null;
            if (type == null || type == "0")
            {
                result = _repository.Find(r => 1 == 1);
            }
            else
            {
                result = _repository.Find(r => r.typeid == type);
            }

            return result.OrderBy(r => r.classify).ThenBy(r => r.typeid).ThenBy(r => r.groupid).ThenBy(r => r.unitid).ToList();
        }
    }

    public class QuestAnswer
    {
        public int ext { get; set; }
        public object remark { get; set; }
        public List<QuestAnswer> answers { get; set; }
        public int Checked {get;set;}
    }

    public class QuestResult
    {
        public int[] pics { get; set; }
        public int total { get; set; }
        public List<QuestAnswer> answers { get; set; }
    }
}
